<template>
  <div ref="chartRef" style="width: 100%; height: 400px;"></div>
</template>

<script setup>
import { onMounted, watch, ref } from 'vue'
import * as echarts from 'echarts'

const props = defineProps({
  klineData: Array, // [{date, open, close, low, high, volume}]
  signals: Array,   // [{date, type: 'buy'|'sell', price}]
  equityCurve: Array // [{date, value}]
})

const chartRef = ref(null)
let chartInstance = null

const renderChart = () => {
  if (!props.klineData || props.klineData.length === 0) return
  const dates = props.klineData.map(item => item.date)
  const values = props.klineData.map(item => [item.open, item.close, item.low, item.high])
  const volumes = props.klineData.map(item => item.volume)

  // 买卖信号
  const buySignals = props.signals?.filter(s => s.type === 'buy') || []
  const sellSignals = props.signals?.filter(s => s.type === 'sell') || []

  // 净值曲线
  const equity = props.equityCurve?.map(item => item.value) || []

  const option = {
    tooltip: { trigger: 'axis' },
    legend: { data: ['K线', '净值', '买入', '卖出'] },
    grid: { left: '8%', right: '8%', bottom: '15%' },
    xAxis: [
      { type: 'category', data: dates, scale: true, boundaryGap: false, axisLine: { onZero: false } },
      { type: 'category', data: dates, gridIndex: 1, show: false }
    ],
    yAxis: [
      { scale: true, type: 'value', name: '价格' },
      { scale: true, type: 'value', name: '净值', position: 'right', offset: 60 }
    ],
    dataZoom: [
      { type: 'inside', xAxisIndex: [0, 1], start: 80, end: 100 },
      { show: true, xAxisIndex: [0, 1], type: 'slider', top: '90%' }
    ],
    series: [
      {
        name: 'K线',
        type: 'candlestick',
        data: values,
        itemStyle: { color: '#ec0000', color0: '#00da3c', borderColor: '#8A0000', borderColor0: '#008F28' }
      },
      {
        name: '净值',
        type: 'line',
        yAxisIndex: 1,
        data: equity,
        smooth: true,
        showSymbol: false,
        lineStyle: { color: '#5470C6', width: 2 }
      },
      {
        name: '买入',
        type: 'scatter',
        data: buySignals.map(s => [dates.indexOf(s.date), s.price]),
        symbol: 'triangle',
        symbolSize: 12,
        itemStyle: { color: '#ffb400' },
        tooltip: { formatter: p => `买入: ${p.value[1]}` }
      },
      {
        name: '卖出',
        type: 'scatter',
        data: sellSignals.map(s => [dates.indexOf(s.date), s.price]),
        symbol: 'rect',
        symbolSize: 12,
        itemStyle: { color: '#0090ff' },
        tooltip: { formatter: p => `卖出: ${p.value[1]}` }
      }
    ]
  }
  chartInstance?.setOption(option)
}

onMounted(() => {
  chartInstance = echarts.init(chartRef.value)
  renderChart()
})

watch(() => [props.klineData, props.signals, props.equityCurve], renderChart, { deep: true })
</script> 